package com.mk.security.distributed.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.mk.security.distributed.gateway.common.EncryptUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import java.util.*;



@Configuration
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }
    //0代表最优先
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //如果上下文身份信息不是 OAuth2类型那么不进行解析
        if(!(authentication instanceof OAuth2Authentication)){
            return null;
        }
        OAuth2Authentication oAuth2Authentication= (OAuth2Authentication) authentication;
        Authentication userAuthentication=oAuth2Authentication.getUserAuthentication();
        //获取当前用户身份信息
        String principal = userAuthentication.getName();

        //获取当前用户权限信息
        List<String> authorities=new ArrayList<>();
        userAuthentication.getAuthorities().stream().forEach(item->authorities.add(((GrantedAuthority)item).getAuthority()));
        //userAuthentication.getAuthorities().stream().map(item->item.getAuthority()).collect(Collectors.toList());

        //获取请求参数
        OAuth2Request oAuth2Request=oAuth2Authentication.getOAuth2Request();
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String,Object> jsonToken =new HashMap<>(requestParameters);
        if(userAuthentication!=null){
            //身份
            jsonToken.put("principal",principal);
            //权限
            jsonToken.put("authorities",authorities);
        }
        //把身份信息和权限信息放在json中，加入http的header中,转发微服务
        currentContext.addZuulRequestHeader("json-token", EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken)));
        return null;
    }
}
